package com.mazaiting;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.cli.*;

import java.util.Arrays;

/**
 * 命令行参数
 *
 * @author mazaiting
 * @since 2021/8/10
 */
@Slf4j
@Data
public class Cmd {
    /**
     * 帮助标识
     */
    private boolean helpFlag;
    /**
     * 版本标识
     */
    private boolean versionFlag;
    /**
     * Classpath 路径
     */
    private String cpOption;
    /**
     * 类名
     */
    private String className;
    /**
     * 参数
     */
    private String[] args;
    /**
     * JRE目录
     */
    private String xjreOption;


    /**
     * 选项参数
     */
    private static final String HELP = "help";
    private static final String QUESTION_MARK = "?";
    private static final String VERSION = "version";
    private static final String CLASSPATH = "classpath";
    private static final String CP = "cp";
    private static final String X_JRE = "Xjre";


    /**
     * 命令行参数解析
     * @param args 参数
     * @return 命令行参数
     */
    public static Cmd parseCmd(String[] args) {
        try {
            CommandLineParser parser = new DefaultParser();
            Options options = new Options();
            // 添加选项
            options.addOption(HELP, false, "print help message")
                    .addOption(QUESTION_MARK, false, "print help message")
                    .addOption(VERSION, false, "print version and exit")
                    .addOption(CLASSPATH, CLASSPATH)
                    .addOption(CP, CLASSPATH)
                    .addOption(X_JRE, "path to jre");
            // 解析
            CommandLine commandLine = parser.parse(options, args);
            Cmd cmd = new Cmd();
            // 判断选项
            if (commandLine.hasOption(HELP) || commandLine.hasOption(QUESTION_MARK)) {
                cmd.helpFlag = true;
            }
            if (commandLine.hasOption(VERSION)) {
                cmd.versionFlag = true;
            }
            if (commandLine.hasOption(X_JRE)) {
                String[] lineArgs = commandLine.getArgs();
                if (lineArgs.length > 0) {
                    cmd.xjreOption = lineArgs[0];
                    cmd.className = lineArgs[1];
                }
            }
            if (commandLine.hasOption(CP) || commandLine.hasOption(CLASSPATH)) {
                // 获取参数信息
                String[] lineArgs = commandLine.getArgs();
                if (lineArgs.length > 0) {
                    cmd.cpOption = lineArgs[0];
                    cmd.className = lineArgs[1];
                    cmd.args = Arrays.copyOfRange(lineArgs, 2, lineArgs.length);
                }
            }
            return cmd;
        } catch (ParseException e) {
            log.error("Usage: {} [-options] class [args...]", SJava.class.getSimpleName());
            System.exit(0);
            return null;
        }
    }
}


















